package com.springboot.frame.starter.utils;

import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 系统bean帮助类
 *
 * @author madman
 */
public class SpringBeanUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext = null;

    /**
     * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringBeanUtils.applicationContext = applicationContext;
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(String beanname) {
        if (applicationContext == null) {
            return null;
        }
        return (T) applicationContext.getBean(beanname);
    }

    /**
     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
     */
    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    /**
     * 获取上下文
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext;
    }

    /**
     * 手动注入对象
     *
     * @param beanName  bean对象名称
     * @param beanClass bean对象class类型
     */
    private void setBean(String beanName, Class<?> beanClass) {
        DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
        boolean containsBean = defaultListableBeanFactory.containsBean(beanName);
        if (containsBean) {
            defaultListableBeanFactory.removeBeanDefinition(beanName);
        }
        //默认使用对象的无参构造方法：此对象已经重写无参构造（此处会重新实例化一个新对象）
        BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(beanClass);
        //构造注入对象参数
        AbstractBeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();
        beanDefinition.setAutowireMode(2);
        beanDefinition.setPrimary(true);
        beanDefinition.setSynthetic(true);
        beanDefinition.setScope("singleton");
        beanDefinition.setRole(0);
        defaultListableBeanFactory.registerBeanDefinition(beanName, beanDefinition);

    }

}

